var eles = [];

function addEvent(obj, name, fun) {
	if (window.attachEvent) {
		obj.attachEvent("on" + name.toLowerCase(), fun);
	} else {
		obj.addEventListener(name.toLowerCase(), fun, false);
	}
}

function delEvent(obj, name) {
	if (window.removeEventListener) {
		obj.removeEventListener(name, null, false);
	} else {
		obj.detachEvent("on" + name, null);
	}
}

function jsonToElement(json) {
	var te;
	te = eval('new ' + (json.type) + '(' + JSON.stringify(json) + ')');
	eles[json.id] = te;
}
/**
 * 解析事件返回的数据
 * 
 * @param res
 */
function parseResult(res) {
	var currObj;
	if (res) {
		for ( var r in res) {
			var property = res[r].property;
			for ( var t in property) {
				var _type = t;
				if (_type == 'CREATE') {
					jsonToElement(property[t].CREATE);
					currObj = eles[r];
				} else if (_type == 'DEL') {
					eles[r].del();
				} else if (_type == 'ATTRIBUTE') {
					currObj = eles[r];
					for ( var c in property[t]) {
						currObj.attribute(c, property[t][c]);
					}
				} else if (_type == 'CSS') {
					currObj = eles[r];
					for ( var c in property[t]) {
						currObj.css(c, property[t][c]);
					}
				} else {
					MsgBox(currObj.type + ": " + _type).show();
				}
			}
		}
	}

}
/**
 * 创建新元素
 * 
 * @param ele
 * @returns
 */
function createElement(type) {
	return document.createElement(type)
}
/**
 * 添加子元素
 * 
 * @param pid
 * @param ele
 */
function addEle(pid, ele, bEle) {
	var _ele = document.getElementById(pid);
	if (_ele) {
		if (bEle == undefined) {
			_ele.appendChild(ele);
		} else {
			_ele.insertBefore(ele, bEle);
		}
	} else {
		if (bEle == undefined) {
			document.body.appendChild(ele);
		} else {
			document.body.insertBefore(ele, bEle);
		}
	}
}
function addEles(pid, eles, bEle) {
	var _ele = document.getElementById(pid);
	for (var i = 0; i < eles.length; i++) {
		if (_ele) {
			if (bEle == undefined) {
				_ele.appendChild(eles[i]);
			} else {
				_ele.insertBefore(eles[i], bEle);
			}
		} else {
			if (bEle == undefined) {
				document.body.appendChild(eles[i]);
			} else {
				document.body.insertBefore(eles[i], bEle);
			}
		}
	}
}

function initPage(obj) {
	parseResult(obj.eventResult);
}
/**
 * 初始事件
 * 
 * @param ele
 * @param obj
 */
function initEvent(ele, obj) {
	var e = obj.event;
	if (e) {
		for ( var o in e) {
			addEvent(ele.uiEle, e[o].eventType, function event() {
				var res = execRequest("event", {
					type : e[o].eventType,
					id : obj.id,
					param : ele.eventParam()
				}, false, "POST");
				parseResult(res);
			});
		}
	}
}
